package net.narusas.aceauction.push.myhomeapp;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.SwingUtilities;

import net.narusas.aceauction.push.APSNPushService;
import net.narusas.aceauction.push.C2DMPushService;
import net.narusas.aceauction.push.db.DeviceDAO;
import net.narusas.aceauction.push.db.GoodsSearchDAO;
import net.narusas.aceauction.push.model.Device;

import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Main {
	private UI ui;
	private FileSystemXmlApplicationContext ctxt;
	private DeviceDAO deviceDao;
	private GoodsSearchDAO goodsSearchDao;
	private APSNPushService apsnPushService;
	private C2DMPushService c2dmPushService;

	public Main() {
		ctxt = new FileSystemXmlApplicationContext("cfg/spring.cfg.xml");
		deviceDao = (DeviceDAO) ctxt.getBean("deviceDAO");
		goodsSearchDao = (GoodsSearchDAO) ctxt.getBean("goodsSearchDAO");
		apsnPushService = (APSNPushService) ctxt.getBean("apsnPushService");
		c2dmPushService = (C2DMPushService) ctxt.getBean("c2dmPushService");

		ui = new UI();
		ui.btnStart.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				new Thread() {
					@Override
					public void run() {
						startJob();
					}
				}.start();
			}
		});
		ui.setVisible(true);

	}

	protected void startJob() {
		log("작업을 시작합니다.");
		List<Device> devices = deviceDao.getAll();
		
		log(devices.size() + "대의 스마트폰을 대상으로 동작합니다");
		for (Device device : devices) {
			send(device);
		}
		log("작업을 종료합니다.");

	}

	private void send(Device device) {
		try {
			if (device.isSendable() == false) {
				log("대상 기기:" + device.getId() + "는 주소정보가 없습니다. ");
				return;
			}
			int badge = goodsSearchDao.badgeOf(device);

			log("대상 기기:" + device.getId() + " 검색된 물건 수:" + badge +" 기타기기정보:"+device);
			if (device.isIOSDevice()) {
				apsnPushService.pushBadge(device, badge);
			}
			if (device.isAndroidSDevice()){
				c2dmPushService.pushBadge(device, badge);
			}
		} catch (Exception e) {
			log("오류:"+e.getMessage());
			e.printStackTrace();
		}
	}

	void log(String text) {
		String old = ui.textArea.getText();
		if (old == null) {
			old = "";
		}
		final String newText = old + text + "\n";
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				ui.textArea.setText(newText);
				ui.textArea.setCaretPosition(newText.length());
			}
		});

	}

	public static void main(String[] args) {
		new Main();

	}
}

